package neuedu;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @description: CAS乐观锁的实现
 * @author: Peng Jiwei
 * @create :2021/10/22-16:43
 */
public class Demo1 implements Runnable{
    private int count = 0;
    public static AtomicInteger count1 = new AtomicInteger(0);
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName()+"开始操作前 count="+count1);
            add();
            System.out.println(Thread.currentThread().getName()+"操作后 count="+count1);
            try {
                Thread.sleep(300);  //延时0.3秒
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args)  {
        Demo1 demo1 = new Demo1();
        new Thread(demo1,"线程1").start();
        new Thread(demo1,"线程2").start();


    }

    //一开始未加锁之前

//    public void add(){
//        this.count++;
//    }

    //加锁之后
//    public synchronized void add(){
//        this.count++;
//    }

    public void add(){
        count1.incrementAndGet();
    }
}
